package com.web.Filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //request获取session判断是否登录成功！
        HttpServletRequest req=(HttpServletRequest) request;

        //创建URL数组 不屏蔽登录相关URL

        String[] urls={"/LoginServlet","/RegisterServlet","/Login.jsp","/register.html"};

        String s = req.getRequestURL().toString();

        for (String url : urls) {
            if(url.contains(s))
            {
                //如果路径包含则放行

                chain.doFilter(request, response);
                return;
            }
        }

        //获取session
        HttpSession session = req.getSession();

        //获取session对象值
        Object user = session.getAttribute("user");


        //如果user对象存在
        if(user!=null)
        {
            //放行
            chain.doFilter(request, response);
        }else{
            //user对象不存在
            req.getRequestDispatcher("/Login.jsp").forward(request,response);
        }


    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }


}
